#include "MusicCache.h"

MusicCache* MusicCache::m_musicCache = NULL;

MusicCache::MusicCache()
{
    //ctor
}

MusicCache::~MusicCache()
{
    //dtor
}


/* GetSingleton */
MusicCache* MusicCache::GetMusicCache()
{
	if (not m_musicCache)
        m_musicCache = new MusicCache();
	return m_musicCache;
}

Music* MusicCache::GetMusic(string musicName)
{
    Music *music;
    map<string, Music *>::iterator iter;

    iter = m_music.find(musicName);
    if (iter == m_music.end())
    {
        // Music was not found, let's try to create it
        string filename = "musics/" + musicName + ".wav";

        music = new Music();
        if (music->loadMusic(filename) == PENJIN_OK) {
            m_music[musicName] = music;
            return music;
        }
        return NULL;
    } else {
        return iter->second;
    }
}

void MusicCache::AddMusic(string musicName, string musicFilename)
{
    Music *music;

    map<string, Music *>::iterator iter;

    iter = m_music.find(musicName);
    if (iter == m_music.end())
    {
        music = new Music();
        if (music->loadMusic(musicFilename) == PENJIN_OK) {
            m_music[musicName] = music;
        }
    } // else we already have it, so do nothing
};

void MusicCache::AddMusic(string musicName)
{
    Music *music;

    map<string, Music *>::iterator iter;

    iter = m_music.find(musicName);
    if (iter == m_music.end())
    {
        string filename = "music/" + musicName + ".mp3";
        music = new Music();
        if (music->loadMusic(filename) == PENJIN_OK) {
            m_music[musicName] = music;
        }
    } // else we already have it, so do nothing
};

void MusicCache::PlayMusic(string musicName)
{
    if (m_currentMusic) {
        if (m_currentMusic->isPlaying()) m_currentMusic->fade(2000);
    }
    Music *music = GetMusic(musicName);
    if (music) {
        if (m_currentMusic) {
            music->playFadeIn(2000);
        } else {
            music->play();
        }
        m_currentMusic = music;
    }
};

void MusicCache::PlayMusic(string musicName, CRuint volume)
{
    if (m_currentMusic) {
        if (m_currentMusic->isPlaying()) m_currentMusic->fade(2000);
    }
    Music *music = GetMusic(musicName);
    if (music) {
        music->setVolume(volume);
        if (m_currentMusic) {
            music->playFadeIn(2000);
        } else {
            music->play();
        }
        m_currentMusic = music;
    }
};

void MusicCache::TogglePauseMusic()
{
    if (m_currentMusic)
    {
        m_currentMusic->playPause();
    }
}

void MusicCache::Clear()
{
    map<string, Music *>::iterator iter;

    for (iter = m_music.begin(); iter != m_music.end(); ++iter)
    {
        delete iter->second;
    }
    m_music.clear();
    m_currentMusic = NULL;
};
